package com.carboy.launch.activity.setting;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.carboy.launch.BaseApplication;
import com.carboy.launch.R;
import com.carboy.launch.able.AbstractDialogOperate;
import com.carboy.launch.activity.column.BaseActivity;
import com.carboy.launch.adapter.setting.WifiAdapter;
import com.carboy.launch.db.DbManager;
import com.carboy.launch.log.LogOutput;
import com.carboy.launch.utils.Tool;
import com.carboy.launch.widgets.CustomToast;
import com.carboy.launch.widgets.WifiConnectOperateDialog;

/**
 * wifi设置Activity
 */
public class SWifiSettingActivity extends BaseActivity implements
		OnClickListener {

	private Method dataConnSwitchmethod;
	private Class telephonyManagerClass;
	private Object ITelephonyStub;
	private Class ITelephonyClass;

	// 当前上下文
	private Context mContext;

	// ================== 控件View =================
	private ImageView asws_break_igview; // 返回按钮
	private ToggleButton asws_switch_togglebtn, dataconnection_togglebtn; // 开关wifi按钮
	private LinearLayout asws_switch_linear; // 当前连接wifi_Linear
	private ImageView asws_tick_igview; // 连接成功
	private ProgressBar asws_load_pBar; // 连接中
	private TextView asws_wname_tv; // 连接中的wifi名
	private ImageView asws_details_igview; // 红色感叹号,详情
	private ImageView asws_rlevel_igview; // 当前信号级别
	private ImageView asws_lock_igview; // 是否需要密码(是否开放)
	private TextView asws_shint_tv; // 对应的wifi提示
	private ListView asws_listview; // 显示附近wifi
	private ProgressBar asws_pBar; // 提示刷新中
	// ================== 其他对象 =================
	private WifiManager wifiManager; // wifi连接管理类
	private WifiInfo wifiInfo; // 获取已建立连接的wifi信息
	private List<ScanResult> listScanResults = new ArrayList<ScanResult>(); // 获取附近wifi数据
	private List<WifiConfiguration> listWifiConfigs = new ArrayList<WifiConfiguration>(); // 获取手机中保存过配置的连接信息
	private WifiAdapter wifiAdapter; // wifi适配器
	private boolean isConnection = false; // 判断是否连接
	private boolean isConnectionIn = false; // 判断是否连接中
	private WifiConnectOperateDialog wifiConnectODialog; // wifi连接操作dialog
	private AbstractDialogOperate absDialogOperate; // Dialog操作抽象类
	private ScanResult cSResult = null; // 当前操作的wifi
	private WifiConfiguration cWConfig; // 当前操作的连接
	private WifiStateChanageReceiver mWifiStateChanageReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_wifi_setting);
		mContext = SWifiSettingActivity.this;
		initViews();
		initStatusBar();
		initValues();
		initListeners();

	}

	/**
	 * 初始化控件
	 */
	private void initViews() {
		asws_break_igview = (ImageView) this
				.findViewById(R.id.asws_break_igview); // 返回按钮
		asws_switch_togglebtn = (ToggleButton) this
				.findViewById(R.id.asws_switch_togglebtn); // 开关wifi按钮
		dataconnection_togglebtn = (ToggleButton) this
				.findViewById(R.id.dataConnection_togglebtn); // 开关数据连接按钮
		if (isOpenDataConnection(mContext, null)) {
			dataconnection_togglebtn.setChecked(true);
			dataconnection_togglebtn.setEnabled(true);
		} else {
			dataconnection_togglebtn.setChecked(false);
			dataconnection_togglebtn.setEnabled(true);
		}
		asws_switch_linear = (LinearLayout) this
				.findViewById(R.id.asws_switch_linear); // 当前连接wifi_Linear
		asws_load_pBar = (ProgressBar) this.findViewById(R.id.asws_load_pBar); // 连接中
		asws_tick_igview = (ImageView) this.findViewById(R.id.asws_tick_igview); // 连接成功
		asws_wname_tv = (TextView) this.findViewById(R.id.asws_wname_tv); // 连接中的wifi名
		asws_details_igview = (ImageView) this
				.findViewById(R.id.asws_details_igview); // 红色感叹号,详情
		asws_rlevel_igview = (ImageView) this
				.findViewById(R.id.asws_rlevel_igview); // 当前信号级别
		asws_lock_igview = (ImageView) this.findViewById(R.id.asws_lock_igview); // 是否需要密码(是否开放)
		asws_shint_tv = (TextView) this.findViewById(R.id.asws_shint_tv); // 对应的wifi提示
		asws_listview = (ListView) this.findViewById(R.id.asws_listview); // 显示附近wifi
		asws_pBar = (ProgressBar) this.findViewById(R.id.asws_pBar); // 提示刷新中
	}

	/**
	 * 初始化参数
	 */
	private void initValues() {
		// 初始化连接wifi_dialog
		wifiConnectODialog = new WifiConnectOperateDialog(mContext);
		absDialogOperate = new AbstractDialogOperate() {
			@Override
			public void executeWifiConnectOperate(boolean isOperate,
					boolean isOpen, String pwd) {
				wifiConnectODialog.cancelDialog(); // 关闭提示框
				isConnectionIn = false; // 设置为未连接中
				isConnection = false; // 设置为未连接
				if (isOperate) { // 连接
					// 如果wifi没打开，则无视
					if (wifiManager == null || !wifiManager.isWifiEnabled()) {
						// 设置为其他结果
						LogOutput.d("Line -- 123");
						changeConnectTypeView(3);
						return;
					}
					// 进行连接
					dialogConnect(pwd, cSResult.capabilities);
				}
			}
		};
		// 绑定操作触发
		wifiConnectODialog.setAbsDialogOperate(absDialogOperate);
		// 初始化wifi管理类
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		/** 绑定广播 */
		IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		mWifiStateChanageReceiver = new WifiStateChanageReceiver();
		registerReceiver(mWifiStateChanageReceiver, filter);
		// 初始化适配器,并绑定
		wifiAdapter = new WifiAdapter(mContext, listScanResults);
		asws_listview.setAdapter(wifiAdapter);
	}

	/**
	 * 初始化事件
	 */
	private void initListeners() {
		asws_switch_togglebtn.setOnClickListener(this);
		asws_switch_linear.setOnClickListener(this);
		dataconnection_togglebtn.setOnClickListener(this);
		asws_break_igview.setOnClickListener(this);
		asws_listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> aView, View view, int pos,
					long id) {
				BaseApplication.playClickVoice(mContext);
				if (isConnectionIn) { // 如果正在连接中则跳过
					CustomToast.showToast(mContext, "请稍等,连接中..");
					return;
				}
				// 当前点击的wifi
				ScanResult scanResult = listScanResults.get(pos);
				// 保存点击的wifi
				cSResult = scanResult;
				// 如果已经连接了,则判断点击的是否与连接的SSID一致
				if (isConnection) {
					String cBSSID = wifiInfo.getBSSID(); // 连接的BSSID
					String rBSSID = scanResult.BSSID; // 点击的BSSID
					// 如果一样则跳过
					if (cBSSID.equals(rBSSID)) { // 查看已连接wifi信息

						CustomToast.showToast(mContext, "您已连接此wifi");
					} else {
						itemConnect(); // 进行连接
					}
				} else {
					itemConnect(); // 进行连接
				}
			}
		});
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.asws_break_igview:
			SWifiSettingActivity.this.finish();
			break;
		case R.id.asws_switch_togglebtn:
			BaseApplication.playClickVoice(mContext);
			isOpenWifi(asws_switch_togglebtn.isChecked());
			break;
		case R.id.dataConnection_togglebtn:
			BaseApplication.playClickVoice(mContext);
			setDataConnectionState(mContext,
					dataconnection_togglebtn.isChecked());
			break;
		case R.id.asws_switch_linear:
			// 弹出对话框
			ShowCancelDialog(wifiManager);
			break;
		}
	}

	/**
	 * 重写返回键
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SWifiSettingActivity.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onPause() {
		super.onPause();

		try {
			wifiTime.cancel();
		} catch (Exception e) {
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mWifiStateChanageReceiver);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// Activity被回收,则保存数据
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// 切屏触发
	}

	// ============================ wifi操作
	// ======================================
	/**
	 * 判断是否打开wifi
	 */
	private void isOpenWifi(boolean isOpen) {
		if (isOpen) { // 打开wifi
			if (!wifiManager.isWifiEnabled()) {
				 if(isApEnabled(mContext)){ // 如果热点打开了，则关闭热点
					 Tool.setWifiApEnabled(this, wifiManager, false);
				 }
				wifiManager.setWifiEnabled(true);
			}
		} else { // 关闭wifi
			if (wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(false);
			}
		}
	}

	public static boolean isOpenDataConnection(Context pContext, Object[] arg) {

		try {

			ConnectivityManager mConnectivityManager = (ConnectivityManager) pContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			Class ownerClass = mConnectivityManager.getClass();

			Class[] argsClass = null;
			if (arg != null) {
				argsClass = new Class[1];
				argsClass[0] = arg.getClass();
			}

			Method method = ownerClass.getMethod("getMobileDataEnabled",
					argsClass);

			Boolean isOpen = (Boolean) method.invoke(mConnectivityManager, arg);

			return isOpen;

		} catch (Exception e) {
			// TODO: handle exception

			System.out.println("得到移动数据状态出错");
			return false;
		}
	}

	public void setDataConnectionState(Context cxt, boolean state) {
		ConnectivityManager connectivityManager = null;
		Class connectivityManagerClz = null;
		try {
			connectivityManager = (ConnectivityManager) cxt
					.getSystemService("connectivity");
			connectivityManagerClz = connectivityManager.getClass();
			Method method = connectivityManagerClz.getMethod(
					"setMobileDataEnabled", new Class[] { boolean.class });
			method.invoke(connectivityManager, state);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * wifi状态改变广播监听
	 */
	class WifiStateChanageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 监听wifi的打开与关闭，与wifi的连接无关
			if (WifiManager.WIFI_STATE_CHANGED_ACTION
					.equals(intent.getAction())) {
				int wifiState = intent.getIntExtra(
						WifiManager.EXTRA_WIFI_STATE, 0);
				switch (wifiState) {
				case WifiManager.WIFI_STATE_ENABLED: // 已打开
					// 显示对应的数据
					asws_switch_togglebtn.setChecked(true); // 设置为已打开
					asws_switch_togglebtn.setEnabled(true); // 开放按钮
					asws_pBar.setVisibility(View.VISIBLE); // 显示加载中
					asws_listview.setVisibility(View.GONE); // 隐藏附近wifi信息
					asws_shint_tv.setText(R.string.select_wifi_hint); // 设置wifi提示

					setTimeParam(); // 开启定时器
					break;
				case WifiManager.WIFI_STATE_ENABLING: // 正在打开
					CustomToast.showToast(context, "正在打开wifi..");
					// 打开中初始化提示
					asws_shint_tv.setText("正在打开wifi..."); // 设置wifi提示
					asws_switch_togglebtn.setEnabled(false); // 禁止使用
					break;
				case WifiManager.WIFI_STATE_DISABLED: // 已关闭
					// 清空数据

					if (listScanResults != null) {
						listScanResults.clear();
					}
					if (listWifiConfigs != null) {
						listWifiConfigs.clear();
					}

					wifiInfo = null;
					// 设置按钮操作
					asws_switch_togglebtn.setChecked(false); // 设置为未打开
					asws_switch_togglebtn.setEnabled(true); // 开放按钮
//					asws_shint_tv.setText(R.string.wifi_switch_hint); // 设置wifi提示
					break;
				case WifiManager.WIFI_STATE_DISABLING: // 正在关闭
					CustomToast.showToast(context, "正在关闭wifi..");
					// 正在关闭,则先把东西重置
					asws_shint_tv.setText("正在关闭wifi..."); // 设置wifi提示
					asws_switch_togglebtn.setEnabled(false); // 禁止使用
					asws_pBar.setVisibility(View.INVISIBLE); // 隐藏加载中
					asws_listview.setVisibility(View.GONE); // 隐藏附近wifi信息
					asws_switch_linear.setVisibility(View.GONE); // 隐藏已连接wifi信息
					break;
				case WifiManager.WIFI_STATE_UNKNOWN: // 未知
					break;
				}
			}

			// 这个监听wifi的连接状态即是否连上了一个有效无线路由，
			// 当上边广播的状态是WifiManager.WIFI_STATE_DISABLING，和WIFI_STATE_DISABLED的时候，根本不会接到这个广播。
			// 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播，当然刚打开wifi肯定还没有连接到有效的无线
			if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent
					.getAction())) {
				Parcelable parcelableExtra = intent
						.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				if (parcelableExtra != null) {
					NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
					State state = networkInfo.getState(); // 获取网络状态
					boolean isConnected = state == State.CONNECTED;// 获取连接状态
					if (isConnected) {
						// 设置为已连接
						changeConnectTypeView(0);
						setWifiData(); // 设置数据
					} else {
						if (isConnectionIn) {

						} else {
							LogOutput.d("Line -- 337");
							changeConnectTypeView(3);
						}
					}
				}
			}
		}
	}

	/** 设置wifi数据 */
	private void setWifiData() {
		wifiInfo = wifiManager.getConnectionInfo(); // 获取已连接wifi信息
		if (wifiInfo != null) {
			if (wifiInfo.getNetworkId() != -1 && wifiInfo.getLinkSpeed() != -1
					&& (wifiInfo.getIpAddress() != 0)) {
				// 设置信号强度
				setLevelImage(asws_rlevel_igview,
						wifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5));
				// 设置wifi名
				String ssid = wifiInfo.getSSID();
				String tSSID = ssid; // 临时操作 SSID
				int sLength = ssid.length();
				if (sLength != 0) {
					tSSID = tSSID.substring(1, tSSID.length() - 1);
					// 判断是否存在密码
					for (WifiConfiguration wifiConfig : listWifiConfigs) {
						if (wifiConfig.SSID.equals(ssid)) {
							if (wifiConfig.preSharedKey == null) {
								asws_lock_igview.setVisibility(View.GONE);
							} else {
								asws_lock_igview.setVisibility(View.VISIBLE);
							}
							break;
						}
					}
				}
				asws_wname_tv.setText(tSSID); // 显示wifi_SSID
				// 设置为已连接
				changeConnectTypeView(0);
			}
		} else {
			// 设置为其他结果
			LogOutput.d("Line -- 376");
			changeConnectTypeView(3);
		}
	}

	/** 设置显示连接中WIFI数据 */
	private void setScanResultDisplay() {
		// 设置信号强度
		setLevelImage(asws_rlevel_igview,
				wifiManager.calculateSignalLevel(cSResult.level, 5));
		// 设置是否安全
		if (this.isCapabilities(cSResult.capabilities) == 0) {
			asws_lock_igview.setVisibility(View.GONE);
		} else {
			asws_lock_igview.setVisibility(View.VISIBLE);
		}
		asws_wname_tv.setText(cSResult.SSID);
	}

	/** 设置对应的信号强度图片 */
	private void setLevelImage(ImageView imageView, int level) {
		switch (level) {
		case 0:
			imageView.setBackgroundResource(R.drawable.icon_rssi_level_0);
			break;
		case 1:
			imageView.setBackgroundResource(R.drawable.icon_rssi_level_0);
			break;
		case 2:
			imageView.setBackgroundResource(R.drawable.icon_rssi_level_1);
			break;
		case 3:
			imageView.setBackgroundResource(R.drawable.icon_rssi_level_2);
			break;
		case 4:
			imageView.setBackgroundResource(R.drawable.icon_rssi_level_3);
			break;
		}
	}

	/** 显示提示框 */
	private void showDialog(ScanResult scanResult) {
		// 查看信号强度
		int rLevel = wifiManager.calculateSignalLevel(scanResult.level, 3);
		String strength = null;
		switch (rLevel) {
		case 0:
			strength = getResources().getString(R.string.wifi_sign_level_weak);
			break;
		case 1:
			strength = getResources().getString(R.string.wifi_sign_level_normal);
			break;
		case 2:
			strength = getResources().getString(R.string.wifi_sign_level_batter);
			break;
		}
		// 显示提示框
		wifiConnectODialog.showDialog(scanResult.SSID,
				(this.isCapabilities(scanResult.capabilities) == 0), strength);
	}

	/** 查看以前是否也配置过这个网络 */
	private WifiConfiguration isExsits(String SSID) {
		WifiConfiguration config = null;
		for (WifiConfiguration wConfig : listWifiConfigs) {
			if (wConfig != null) {
				if (wConfig.SSID.equals("\"" + SSID + "\"")) {
					config = wConfig;
				}
			}
		}
		if (config == null) {
			// 判断本地是否保存
			DBWifiConfig dbWifiConfig = DbManager.GetWifiConfig(SSID);
			if (dbWifiConfig != null) {
				int model = this.isCapabilities(dbWifiConfig.getMode());
				String password = dbWifiConfig.getPassword();
				config = createWifiInfo(SSID,password, model);
			}
		}
			return config;
		
	}

	/** 点击Item进行连接操作 */
	private void itemConnect() {
		// 先判断是否连接过
		WifiConfiguration wifiConfig = isExsits(cSResult.SSID);
		if (wifiConfig != null) { // 连接过则直接再次连接
			int networkId = wifiManager.addNetwork(wifiConfig);
			wifiConfig.networkId = networkId;
			wifiManager.enableNetwork(networkId, true); // 创建连接,并自动连接
		
			// 设置连接中wifi数据显示
			setScanResultDisplay();
			// 设置为连接中
			changeConnectTypeView(1);

			cWConfig = wifiConfig;
			setCTimeParam();
		} else { // 没连接过则提示输入密码
			showDialog(cSResult);
		}
	}

	/**
	 * 连接wifi结果
	 * 
	 * @param pwd
	 *            密码
	 * @param isOpen
	 *            是否开放
	 * @return
	 */
	private void dialogConnect(String pwd, String capabilities) {
		try {
			// 获取连接对象
			WifiConfiguration wifiConfig = createWifiInfo(cSResult.SSID, pwd,
					this.isCapabilities(capabilities));
			// 添加到配置中
			int netID = wifiManager.addNetwork(wifiConfig);
//			Toast.makeText(mContext,"id"+netID, 3000).show();

			wifiConfig.networkId = netID;
			// 进行连接
			boolean iscon = wifiManager.enableNetwork(netID, true);
			if (iscon) {
				DBWifiConfig dbWifiConfig = new DBWifiConfig();
				dbWifiConfig.setSsid(cSResult.SSID);
				dbWifiConfig.setPassword(pwd);
				dbWifiConfig.setMode(capabilities);
				DbManager.InsertWifiConfig(dbWifiConfig);
			}
			// 设置连接中wifi数据显示
			setScanResultDisplay();
			// 设置为连接中
			changeConnectTypeView(1);

			cWConfig = wifiConfig;
			setCTimeParam();
		} catch (Exception e) {
			// 设置为其他结果
			LogOutput.d("Line -- 486");
			changeConnectTypeView(3);
		}
	}

	/**
	 * 检查对应的加密方式
	 * 
	 * @param capabilities
	 *            传入加密类型
	 * @return
	 */
	private int isCapabilities(String capabilities) {
		int isWap = capabilities.indexOf("WPA"); // 判断是否wpa方式
		if (isWap != -1) {
			return 2;
		}

		int isWep = capabilities.indexOf("WEP"); // 判断是否Wep方式
		if (isWep != -1) {
			return 1;
		}

		int isEss = capabilities.indexOf("ESS"); // 判断是否开放
		if (isEss != -1) {
			return 0;
		}
		return 0;
	}

	/**
	 * 连接wifi
	 * 
	 * @param SSID
	 *            wifi名
	 * @param Password
	 *            wifi密码
	 * @param mode
	 *            连接类型 1.无密码,2.wep方式,3.wpa方式
	 * @return
	 */
	private WifiConfiguration createWifiInfo(String SSID, String Password,
			int mode) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";
		switch (mode) {
		case 0: // WIFICIPHER_NOPASS
			// config.wepKeys[0] = "";
			// config.wepTxKeyIndex = 0;
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			break;
		case 1: // WIFICIPHER_WEP
			config.hiddenSSID = true;
			config.wepKeys[0] = "\"" + Password + "\"";
			config.allowedAuthAlgorithms
					.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
			break;
		case 2: // WIFICIPHER_WPA
			config.preSharedKey = "\"" + Password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms
					.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers
					.set(WifiConfiguration.PairwiseCipher.TKIP);
			// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers
					.set(WifiConfiguration.PairwiseCipher.CCMP);
			config.status = WifiConfiguration.Status.ENABLED;
			break;
		}
		return config;
	}

	// =========================== View操作 =====================================
	/** 设置顶部连接View */
	private void changeConnectTypeView(int type) {
		boolean isCloseTime = false; // 判断是否关闭定时器
		switch (type) {
		case 0: // 已经连接成功,显示对应的wifi
			// 设置为已连接,并且非连接中
			isConnection = true;
			isConnectionIn = false;
			isCloseTime = true; // 关闭定时器
			asws_tick_igview.setVisibility(View.VISIBLE); // 显示连接成功
			asws_load_pBar.setVisibility(View.GONE); // 隐藏转圈加载
			asws_switch_linear.setVisibility(View.VISIBLE); // 显示已连接wifi信息
			break;
		case 1: // 连接中
			// 设置为未连接,并且为连接中
			isConnection = false;
			isConnectionIn = true;
			isCloseTime = false; // 不关闭定时器
			asws_tick_igview.setVisibility(View.GONE); // 隐藏连接成功
			asws_load_pBar.setVisibility(View.VISIBLE); // 显示转圈加载
			asws_switch_linear.setVisibility(View.VISIBLE); // 显示正在连接wifi信息
			break;
		default: // 其他可能性
			// 设置为未连接,并且非连接中
			isConnection = false;
			isConnectionIn = false;
			isCloseTime = true; // 关闭定时器
			// 隐藏已连接wifi信息
			asws_switch_linear.setVisibility(View.GONE);
			break;
		}
		try {
			// 关闭定时器,方式为null或者其他情况 如已取消
			if (isCloseTime) {
				wifiTime.cancel();
			}
		} catch (Exception e) {
		}
	}

	// =========================== 定时器操作 ====================================
	/** 设置定时器参数 */
	private void setTimeParam() {
		timer = new Timer(); // 每次重新new 防止被取消
		// 重新生成定时器 防止出现TimerTask is scheduled already 所以同一个定时器任务只能被放置一次
		task = new TimerTask() {
			@Override
			public void run() {
				// 需要做的事:发送消息
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}
		};
		// 0s后执行task,每次经过3.5s再次执行
		timer.schedule(task, 0, 3500);
	}

	Timer timer = null;
	TimerTask task;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				if (msg.what == 1) {
					// wifi管理对象等于null
					if (wifiManager == null)
						wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

					// 判断wifi是否打开
					if (wifiManager.isWifiEnabled()) {
						// 获取已保存的wifi配置信息
						listWifiConfigs = wifiManager.getConfiguredNetworks();
						// 获取附近wifi列表,并且设置数据
						listScanResults = wifiManager.getScanResults();
						for (int i = 0; i < listScanResults.size(); i++) {
							if (listScanResults.get(i).SSID
									.equals("NVRAM WARNING: Err = 0x10")) {
								listScanResults.remove(i);
							}
						}
						if (listScanResults != null
								&& listScanResults.size() != 0) { // 附近存在wifi,并且不等于0
							// 设置数据源,并且刷新适配器
							wifiAdapter.setListScanResults(listScanResults);
							wifiAdapter.notifyDataSetChanged();

							asws_listview.setVisibility(View.VISIBLE); // 显示附近wifi信息
							asws_pBar.setVisibility(View.INVISIBLE); // 隐藏加载中
						} else {
							asws_pBar.setVisibility(View.VISIBLE); // 显示加载中
						}
						// 设置数据`
						setWifiData();
					} else {
						// 没开wifi则关闭掉定时器
						timer.cancel();
						asws_pBar.setVisibility(View.INVISIBLE);
					}
				}
			} catch (Exception e) {
			}
			super.handleMessage(msg);
		};
	};

	/** 监听wifi连接状态 */
	private void setCTimeParam() {
		try {
			wifiTime.cancel();
		} catch (Exception e) {
		}
		wI = 0;
		wifiTime = new Timer(); // 每次重新new 防止被取消
		// 重新生成定时器 防止出现TimerTask is scheduled already 所以同一个定时器任务只能被放置一次
		wifiTask = new TimerTask() {
			@Override
			public void run() {
				// 需要做的事:发送消息
				Message message = new Message();
				message.what = 1;
				wifiHandler.sendMessage(message);
			}
		};
		// 0s后执行task,每次经过3.5s再次执行
		wifiTime.schedule(wifiTask, 500, 500);
	}

	int wI = 0;
	Timer wifiTime = null;
	TimerTask wifiTask;
	Handler wifiHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				// 5秒内无响应则关闭
				if (wI >= 10) {
					wifiTime.cancel();
					if (isConnectionIn) { // 未连接则设置隐藏,并移除
						LogOutput.d("Line -- 694");
						changeConnectTypeView(3);
						wifiManager.removeNetwork(cWConfig.networkId);
					}
					return;
				}
				wI++;
				if (msg.what == 1) {
					// wifi管理对象等于null
					if (wifiManager == null)
						wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

					// 判断wifi是否打开
					if (wifiManager.isWifiEnabled()) {
						setScanResultDisplay();
					} else {
						// 没开wifi则关闭掉定时器
						wifiTime.cancel();
					}
				}
			} catch (Exception e) {
				wifiTime.cancel();
				LogOutput.d("Line -- 723");
				changeConnectTypeView(3);
				wifiManager.removeNetwork(cWConfig.networkId);
			}
			super.handleMessage(msg);
		};
	};

	// ======================= 热点操作 ==============================
	public static final int WIFI_AP_STATE_DISABLING = 10;
	public static final int WIFI_AP_STATE_DISABLED = 11;
	public static final int WIFI_AP_STATE_ENABLING = 12;
	public static final int WIFI_AP_STATE_ENABLED = 13;
	public static final int WIFI_AP_STATE_FAILED = 14;

	// 获取WIFI热点的状态：
	public int getWifiApState(Context mContext) {
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		try {
			Method method = wifiManager.getClass().getMethod("getWifiApState");
			int i = (Integer) method.invoke(wifiManager);
			return i;
		} catch (Exception e) {
			return WIFI_AP_STATE_FAILED; // 启动失败
		}
	}

	// 判断Wifi热点是否可用：
	public boolean isApEnabled(Context mContext) {
		int state = getWifiApState(mContext);
		return WIFI_AP_STATE_ENABLING == state
				|| WIFI_AP_STATE_ENABLED == state;
	}

	public void ShowCancelDialog(final WifiManager wifiManager) {
		final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.dialog_wifi_connected, null);
		TextView t = (TextView) layout.findViewById(R.id.dwc_sintensity_tv);
		int level = wifiManager.calculateSignalLevel(wifiInfo.getRssi(), 3);
		if (level == 2) {
			t.setText(getResources().getString(R.string.wifi_sign_level_batter));
		} else if (level == 1) {
			t.setText(getResources().getString(R.string.wifi_sign_level_normal));
		} else {
			t.setText(getResources().getString(R.string.wifi_sign_level_weak));
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(wifiInfo.getSSID())
				.setView(layout)
				.setPositiveButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {

					}
				})
				.setNegativeButton(getResources().getString(R.string.not_save),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								for (WifiConfiguration wifiConfig : listWifiConfigs) {
									if (wifiConfig.SSID.equals(wifiInfo
											.getSSID())) {
										// 断开连接
										wifiManager.disconnect();
										// 取消保存
										wifiManager.removeNetwork(wifiInfo
												.getNetworkId());
//										//从数据库中删除
										DbManager.deleWifi(wifiConfig.SSID);
										
										wifiManager.reconnect();
										break;
									}
								}

							}
						});

		builder.create().show();
	}
}
